package com.dlc.shop.discount.api.listener;

import cn.hutool.core.collection.CollUtil;
import com.dlc.shop.bean.app.dto.ChooseDiscountItemDto;
import com.dlc.shop.bean.app.dto.ShopCartItemDiscountDto;
import com.dlc.shop.bean.app.dto.ShopCartOrderDto;
import com.dlc.shop.bean.event.SubmitOrderActivityEvent;
import com.dlc.shop.bean.order.SubmitOrderActivityOrder;
import com.dlc.shop.common.exception.YamiShopBindException;
import com.dlc.shop.discount.common.dao.DiscountMapper;
import lombok.AllArgsConstructor;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;

/**
 * 提交订单时检查下满减活动状态
 * @author LGH
 */
@Component("CheckDiscountStatusListener")
@AllArgsConstructor
public class SubmitOrderActivityListener {

    private final DiscountMapper discountMapper;

    @EventListener(SubmitOrderActivityEvent.class)
    @Order(SubmitOrderActivityOrder.DISCOUNT)
    public void checkDiscountStatusListener(SubmitOrderActivityEvent event) {
        List<ShopCartOrderDto> shopCartOrders = event.getShopCartOrderMergerDto().getShopCartOrders();
        Set<Long> discountIds = new HashSet<>();
        //获取已经选择的所有满减活动
        for (ShopCartOrderDto shopCartOrder : shopCartOrders) {
            List<ShopCartItemDiscountDto> shopCartItemDiscounts = shopCartOrder.getShopCartItemDiscounts();
            if (CollUtil.isNotEmpty(shopCartItemDiscounts)) {
                for (ShopCartItemDiscountDto shopCartItemDiscount : shopCartItemDiscounts) {
                    ChooseDiscountItemDto chooseDiscountItemDto = shopCartItemDiscount.getChooseDiscountItemDto();
                    if (Objects.nonNull(chooseDiscountItemDto)) {
                        discountIds.add(chooseDiscountItemDto.getDiscountId());
                    }
                }
            }
        }
        if (CollUtil.isEmpty(discountIds)) {
            return;
        }
        int num = discountMapper.countNormalDiscount(discountIds);
        if (num < discountIds.size()) {
            //当前选择的满减活动已经过期，请返回重新提交订单
            throw new YamiShopBindException("yami.order.discount.expire.check");
        }
    }
}
